//
//  STHomeViewController.swift
//  RouterPushProtocol
//
//  Created by Toj on 2/21/22.
//

import UIKit
import TTCOM_iOS
import CoreLocation

class STHomeViewController: STBaseViewController {
    
    override var pagePath: String {
        return "startimes://home"
    }
    
    private let viewModel = HomeViewModel()
    
    private lazy var testButton: UIButton = {
        let view = UIButton()
        view.setTitle("开始", for: .normal)
        view.addTarget(self, action: #selector(didTapTest), for: .touchUpInside)
        return view
    }()
    
    private lazy var testButton2: UIButton = {
        let view = UIButton()
        view.setTitle("结束", for: .normal)
        view.backgroundColor = .white
        view.addTarget(self, action: #selector(didTapTest2), for: .touchUpInside)
        return view
    }()
    
    var timer: Timer?
    
    func deleteSection(at index: Int) -> Bool {
        defer {
            print("deleteSection end")
        }
        
        guard index < 10 else {
            print("deleteSection index < 10")
            return false
        }
        
        print("deleteSection index > 10")
        return true
    }
    
    func test2() {
        let ind = 10
        print("-->toj: ind: \(ind)")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        defer {
            print("deleteSection viewDidLoad end")
        }
        
        view.addSubview(testView)
        testView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(100)
            make.height.equalTo(44)
        }
        
        test2()
        
        print("deleteSection viewDidLoad start")
        
        let error = STError.str
        
        print("-->toj: STError.str: \(error)")
        
        viewModel.homeVC = self

        view.backgroundColor = .white
        
        tt_isNavigationBarHidden = true
        testButton.backgroundColor = .blue
        
        view.addSubview(testButton)
        view.addSubview(testButton2)
        testButton2.backgroundColor = .white
        var y = 50 + CGFloat.nav_barFullHeight
        testButton.frame = CGRect(x: 50, y: y, width: 100, height: 100)
        //testButton.cm_cornerRadius = 8
        testButton2.frame = CGRect(x: 200, y: y, width: 100, height: 100)
        let borderColors = [UIColor.green.cgColor]
        
        testButton2.gd_add(colors: borderColors)
        // (radius: 100 * 0.5, border: 3, gradient: borderColors, direction: .horizontal)
        
        CM.absoluteTimes {
            let colors: [CGColor] = [UIColor.gray.cgColor, UIColor.yellow.cgColor]
            self.testButton2.gd_add(colors: colors)
        }
        
        // registerNotification()
        
        _ = deleteSection(at: 1)
        
        _ = deleteSection(at: 11)
        
        print("deleteSection viewDidLoad ---")
        y += 150
        
        view.addSubview(backgroundImageView)
        backgroundImageView.snp.makeConstraints { make in
            make.top.equalTo(y)
            make.left.right.equalTo(view)
            make.height.equalTo(47)
        }
        
        y += 50
        view.addSubview(testImageView)
        testImageView.snp.makeConstraints { make in
            make.top.equalTo(y)
            make.left.right.equalTo(view)
            make.height.equalTo(47)
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now()+3) {
            // 播放中
            // guard  1 == 1 else { return }
            print("-->toj: MediaTime: \(CACurrentMediaTime())")
            self.fpsTimer = Timer(0.1, target: self, selector: #selector(self.updateValues))
        }
    }
    
    var count = 0
    private var displayLink: CADisplayLink?
    private var fpsTimer: Timer?
    @objc func updateValues() {
        count += 1
        guard count < 11 else {
            fpsTimer?.invalidate()
            fpsTimer = nil
            return
        }
        print("-->toj: MediaTime: \(CACurrentMediaTime())")
    }
    
    @objc func willResignActive(sender: Notification) {
        print("-->toj: class:\(cm_objectName), func:" + #function)
    }
    
    // 已经进入后台
    @objc func didEnterBackground(sender: Notification) {
        print("-->toj: class:\(cm_objectName), func:" + #function)
    }
    
    @objc func willEnterForeground(sender: Notification) {
        print("-->toj: class:\(cm_objectName), func:" + #function)
    }
    
    // 已经激活
    @objc func didBecomeActive(sender: Notification) {
        print("-->toj: class:\(cm_objectName), func:" + #function)
    }
    
    
    func registerNotification() {
        print("-->toj: class:\(cm_objectName), func:" + #function)
    
        NotificationCenter.default.addObserver(self, selector: #selector(willResignActive(sender:)), name: UIApplication.willResignActiveNotification, object: nil)
 
        NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground(sender:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive(sender:)), name: UIApplication.didBecomeActiveNotification, object: nil)
     
        NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(sender:)), name: UIApplication.willEnterForegroundNotification, object: nil)
    }
    
    @objc func timerCountDownCallBack() {
        // FloatADManager.manager.requestFloatADS()
        print(#function)
    }
    
    @objc func didTapTest() {
        let vc = STLogViewController()
        navigationController?.pushViewController(vc, animated: true)
//        viewModel.showAppOpenAd()
//
//        return;
        
//        let navigationController = UINavigationController(rootViewController: STSignInViewController.shared)
//        navigationController.setNavigationBarHidden(true, animated: false)
//        navigationController.modalPresentationStyle = .custom
//        present(navigationController, animated: false)
//
        // STSignInViewController.shared.presentController()
        
//        guard gradientTimer == nil else { return }
//        
//        let timer = Timer.st_scheduledTimer(timeInterval: 1, target: self, selector: #selector(gradientRandom), userInfo: nil, repeats: true)
//        gradientTimer = timer
    }
    
    @objc private func gradientRandom() {
        testButton2.gd_remove()
        let random1 = UIColor.random
        let random2 = UIColor.random
        let borderColors = (arc4random_uniform(2) == 1) ? [random1.cgColor, random2.cgColor] : [random1.cgColor]
        testButton2.gd_add(colors: borderColors)
        
        testButton2.layer.sublayers?.forEach({ layer in
            // print("-->toj: layer: \(layer.cm_className)")
        })
    }
    
    var gradientTimer: Timer?
    @objc func didTapTest2() {
        let alertVC = UIAlertController(title: "错误", message: "原因", preferredStyle: .alert)
   
        alertVC.addTextField( configurationHandler: { text in
            text.text = "原因"
        })
        alertVC.addTextField( configurationHandler: { text in
            text.text = "错误"
        })
        
        let action = UIAlertAction(title: "34", style: .cancel)
        alertVC.addAction(action)
        
        present(alertVC, animated: true)
    }
    
    @objc func didTapTest3() {
        let random1 = UIColor.random
        let random2 = UIColor.random
        let borderColors = [random1.cgColor, random2.cgColor]
        let random3 = CGFloat(arc4random_uniform(10))
        let random4 = CGFloat(arc4random_uniform(5))
        
        let random5 = Int(arc4random_uniform(8))
        
        let direction = GADirection(rawValue: random5) ?? .horizontal
        // print("-->toj: direction:\(direction) ,radius:\(random3), border:\(random4)")
        testButton2.gd_add(colors: borderColors, direction: direction, corner: random3)
        
        testButton2.layer.sublayers?.forEach({ layer in
            // print("-->toj: layer: \(layer.cm_className)")
        })
        
        // let keyString = FunctionManager.manager.signatureKeyString
        //
        // let keyString2 = FunctionManager.manager.signatureKeyString
        //
        // let keyString3 = FunctionManager.manager.signatureKeyString
        //
        // let vc = FMTextFieldViewController()
        // navigationController?.pushViewController(vc, animated: true)
    }
    
    private func test() {
        timer?.invalidate()
        timer = nil
        // var s = Date().dm_timestamp_s
        // print("-->toj: " + s)
        //
        //  s = Date().dm_timestamp_ms
        // print("-->toj: " + s)
        //
        // s = Date().dm_timestamp_us
        // print("-->toj: " + s)
        // -->toj: timeOutCount = 1
        // -->toj: userID:53081524, random:19466, timestamp:1654139110180, encrypted:utm_source=union&utm_medium=1|1,
        //
        // userID:53081524, random:10108, timestamp:1654139510576, encrypted:utm_source=union&utm_medium=1|1
        
        // utm_source=union&utm_medium=1|153081524101081654139510576
        // 9C9E492547679A83E62C2A64C908405D0E4ADAFBDC4A2B28DCC5E37D736DBC87
        
        // let format = String.signatureOrder(userID: "53081524", nonce: "10108", timestamp: 1654139510576, encrypted: "utm_source=union&utm_medium=1|1")
        //
        // print("-->toj: format: " + format)
        //
        // let disest = format.cm_hmac(algorithm: .SHA256, key: "key")
        
        // http://qa.upms.startimestv.com/membership/v1/product/73/categorys?nonce=17141&=&timestamp=&utm=utm_source%3Dunion%26utm_medium%3D1%7C1
        // 737DF7602921CAC4947C0B0EE4BED37CD139ACA425CF4F9E07E08B27B0A7AB06
        // print("-->toj: disest: " + disest)
    }
    
    /* <#NOTE#> */
    private lazy var backgroundImageView: UIImageView = {
        let view = UIImageView()
        view.image = "player_product_header_bgimg".to_image
        return view
    }()
    
    /* <#NOTE#> */
    private lazy var testImageView: UIImageView = {
        let view = UIImageView()
        view.image = "test-product_Header".to_image
        return view
    }()
    
    /** <#NOTE#> **/
    private lazy var testView: TSView = {
        let view = TSView()
        view.backgroundColor = .random
        return view
    }()
}

public struct STError: Swift.Error {
    var rawValue: NSError

    static let str = STError(rawValue: NSError(domain: "12345", code: 0, userInfo: ["key": "value"]))
}

class APIConfig: NSObject {
    init?(s: String) throws {
        if s == "taojian" {
            return
        }
        throw STError.str
    }
    
    func headers() -> Dictionary<String, String> {
        // let api = try! APIConfig(s: "12345")
        return [:]
    }
}
